<template>
  <div>
    <el-dialog :visible.sync="dialogVisible" :title="title+'门店'" width="895px">
      <el-form
          :model="supplierInfo"
          :rules="rules"
          ref="supplierForm"
          label-width="0"
      >
        <!--        <div style="display: grid; grid-template-columns: repeat(2, 1fr); grid-gap: 10px;">-->
        <el-form-item prop="storeName">
          <div style="display: flex">
            <p style="width:90px;text-align: right;font-weight: bold">门店名称：</p>
            <el-input size="small" clearable v-model="supplierInfo.storeName" placeholder="请输入">
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="address">
          <div style="display: flex;align-items: center">
            <p style="width:90px;text-align: right;font-weight: bold">门店地址：</p>
            <el-input placeholder="请打开地图选择门店地址" v-model="supplierInfo.address" size="small">
              <template slot="append">
                <el-link @click="openEarth">
                  <i class="el-icon-position"></i>
                </el-link>
              </template>
            </el-input>
            <!--            <div @click="openEarth"-->
            <!--                 style="width: 100px;height: 30px;background-color:#eeeeee;line-height: 30px;border: 1px solid #d9d9d9;font-size: 13px;text-align: center">-->
            <!--              <i-->
            <!--                  class="el-icon-search"></i> 打开地图-->
            <!--            </div>-->
          </div>
        </el-form-item>
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); grid-gap: 0;">
          <el-form-item prop="storeVariety">
            <div style="display: flex; width: 100%;">
              <p style="width: 100px;text-align: right;font-weight: bold">门店品种：</p>
              <el-select
                  size="small"
                  v-model="supplierInfo.storeVariety"
                  placeholder="请选择门店品种"
                  clearable
                  style="width: 100%"
                  prefix-icon="el-icon-search"
              >
                <el-option label="零食店" value="1"></el-option>
                <el-option label="便利店" value="2"></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="storeType">
            <div style="display: flex; width: 100%;">
              <p style="width: 100px;text-align: right;font-weight: bold">门店类型：</p>
              <el-select
                  size="small"
                  v-model="supplierInfo.storeType"
                  placeholder="请选择门店类型"
                  clearable
                  style="width: 100%"
                  prefix-icon="el-icon-search"
              >
                <el-option label="加盟店" value="F"></el-option>
                <el-option label="直营店" value="R"></el-option>
              </el-select>
            </div>
          </el-form-item>
          <!--          <el-form-item prop="value1">-->
          <!--            <div style="display: flex; width: 100%;">-->
          <!--              <p style="width: 100px;text-align: right;font-weight: bold">开工日期：</p>-->
          <!--              <el-date-picker-->
          <!--                  v-model="supplierInfo.value1"-->
          <!--                  type="date"-->
          <!--                  size="small"-->
          <!--                  style="width: 100%"-->
          <!--                  placeholder="请选择日期">-->
          <!--              </el-date-picker>-->
          <!--            </div>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item prop="storeVariety">-->
          <!--            <div style="display: flex; width: 100%;">-->
          <!--              <p style="width: 100px;text-align: right;font-weight: bold">状态：</p>-->
          <!--              <el-select-->
          <!--                  size="small"-->
          <!--                  v-model="supplierInfo.storeVariety"-->
          <!--                  placeholder="请选择装修状态"-->
          <!--                  clearable-->
          <!--                  style="width: 100%"-->
          <!--                  prefix-icon="el-icon-search"-->
          <!--              >-->
          <!--                <el-option label="待进场" value="1"></el-option>-->
          <!--                <el-option label="施工中" value="2"></el-option>-->
          <!--                <el-option label="验收中" value="2"></el-option>-->
          <!--              </el-select>-->
          <!--            </div>-->
          <!--          </el-form-item>-->
          <el-form-item prop="type">
            <div style="display: flex; width: 100%;">
              <p style="width: 100px;text-align: right;font-weight: bold">装修类型：</p>
              <el-select
                  size="small"
                  v-model="supplierInfo.type"
                  placeholder="请选择装修类型"
                  clearable
                  style="width: 100%"
                  prefix-icon="el-icon-search"
              >
                <el-option label="新增店铺" value="1"></el-option>
                <el-option label="老店升级" value="2"></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="storeArea">
            <div style="display: flex; width: 100%;">
              <p style="width: 100px;text-align: right;font-weight: bold">面积：</p>
              <el-input size="small" placeholder="请输入门店面积" v-model="supplierInfo.storeArea">
                <a slot="suffix">㎡</a>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="storePhone">
            <div style="display: flex">
              <p style="width: 100px;text-align: right;font-weight: bold">门店电话：</p>
              <el-input size="small" clearable v-model="supplierInfo.storePhone" placeholder="请输入"
                        :disabled="title=='编辑'">
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="brandPartyId">
            <div style="display: flex; width: 100%;">
              <p style="width: 100px;text-align: right;font-weight: bold">品牌方：</p>
              <el-select
                  size="small"
                  v-model="supplierInfo.brandPartyId"
                  placeholder="请选择所属品牌"
                  clearable
                  style="width: 100%"
                  prefix-icon="el-icon-search"
              >
                <el-option
                    v-for="item in brandList"
                    :key="item.id"
                    :label="item.brandPartyName"
                    :value="item.id"
                />
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="storeUserId">
            <div style="display: flex; width: 100%;" @click="chooseS('S')">
              <p style="width: 100px;text-align: right;font-weight: bold">店长电话：</p>
              <el-input
                  size="small"
                  placeholder="请点击选择店长"
                  :disabled="!supplierInfo.brandPartyId"
                  v-model="supplierInfo.storeUserId"
                  readonly
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="franchiseeId">
            <div style="display: flex; width: 100%;" @click="chooseS('F')">
              <p style="width: 100px;text-align: right;font-weight: bold">加盟商：</p>
              <el-input
                  size="small"
                  :disabled="title=='编辑'||!supplierInfo.brandPartyId"
                  placeholder="请点击选择加盟商"
                  v-model="supplierInfo.franchiseeId"
                  readonly
              ></el-input>
            </div>
          </el-form-item>
        </div>
        <div style="margin-top: 20px; text-align: center;">
          <el-button @click="dialogVisible=false"
                     style="background-color:#F3F6FD;color: #303e9d;width: 100px;height: 40px;font-weight: bold;font-size: 14px"
                     size="small">取 消
          </el-button>
          <el-button @click="_submit"
                     style="background-color:#303e9d;color: #eeeeee;width: 100px;height: 40px;font-weight: bold;font-size: 14px"
                     size="small">保 存
          </el-button>
        </div>
      </el-form>
      <!--      <span slot="footer">-->
      <!--        <el-button @click="dialogVisible=false">取 消</el-button>-->
      <!--        <el-button style="background-color:#303e9d;color: #eeeeee" @click="_submit">确 定</el-button>-->
      <!--      </span>-->
    </el-dialog>
    <init-map ref="initMapD" @addStatus="receiveMessage"></init-map>
    <el-dialog :visible.sync="supplierDialog" :title="typeTitle" modal-append-to-body width="40%" top="50px">
      <span>  姓名：<el-input placeholder="请搜索" size="small" style="width: 180px" v-model="userName" clearable></el-input></span>
      <span style="margin-left: 10px">  电话：<el-input placeholder="请搜索" size="small"
                                                     style="width: 180px" v-model="phoneNum"
                                                     clearable></el-input></span>
      <span style="margin-left: 10px"> <el-button size="small" style="color: #eeeeee"
                                                  @click="getNickList">搜索</el-button></span>
      <el-table :data="supplierData" highlight-current-row
                :cell-style="{ 'textAlign': 'center' }"
                :header-cell-style="{'fontSize': '14px','background-color': '#F3F6FD','color': '#333333','textAlign': 'center' }"
                @selection-change="handleSelectionChange" height="calc(100vh - 380px)">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <div v-if="typeTitle=='加盟商列表'">
          <el-table-column prop="franchiseeName" label="姓名"></el-table-column>
          <el-table-column prop="franchiseePhone" label="电话"></el-table-column>
          <el-table-column prop="gender" label="性别"></el-table-column>
          <el-table-column prop="openNum" label="店铺数量"></el-table-column>
          <el-table-column prop="grade" label="加盟商等级"></el-table-column>
        </div>
        <div v-else>
          <el-table-column prop="storeManagerName" label="姓名"></el-table-column>
          <el-table-column prop="phoneNum" label="电话"></el-table-column>
          <el-table-column prop="gender" label="性别"></el-table-column>
        </div>
      </el-table>
      <span slot="footer">
        <el-button style="color: #eeeeee" @click="comfirm">确定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import initMap from "./initMap.vue";

export default {
  name: "add_storeManage",
  components: {
    initMap
  },
  data() {
    return {
      dialogVisible: false,
      supplierDialog: false,
      typeTitle: "",
      title: '',
      userName: '',
      phoneNum: '',
      supplierInfo: {
        storeName: '',
        address: '',
        storeUserId: "",
        lat: '',
        lon: '',
        type: "",
        storeVariety: '',
        storeType: '',
        storePhone: '',
        storeManagerPhone: "",
        franchiseeId: '',
        brandPartyId: '',
        storeArea: ''
      },
      brandList: [],
      recordInfo: {},
      recordId: "",
      storeId: "",
      supplierData: [],
      supplierList: [],
      rules: {
        storeName: [{required: true, message: '请输入门店名称', trigger: 'blur'}],
        address: [{required: true, message: '请选择门店地址', trigger: 'change'}],
        type: [{required: true, message: '请选择门店地址', trigger: 'change'}],
        storeVariety: [{required: true, message: '请选择门店品种', trigger: 'change'}],
        storeType: [{required: true, message: '请选择门店类型', trigger: 'change'}],
        storePhone: [{required: true, message: '请输入门店电话', trigger: 'blur'}, {
          pattern: /^1[3-9]\d{9}$/,
          message: '请输入有效的手机号码',
          trigger: 'blur'
        }],
        franchiseeId: [{required: true, message: '请选择加盟商', trigger: 'change'}],
        brandPartyId: [{required: true, message: '请选择品牌方', trigger: 'change'}],
        storeArea: [
          {required: true, message: '请输入门店面积', trigger: 'blur'},
          {
            validator(rule, value, callback) {
              const num = parseFloat(value);
              if (!/^\d+(\.\d{1,2})?$/.test(value)) {
                return callback(new Error('请输入合法的正数（最多两位小数）'));
              }
              if (num <= 0) {
                return callback(new Error('面积必须大于 0'));
              }
              callback();
            },
            trigger: 'blur'
          }
        ]
      },
    }
  },
  methods: {
    getNickList() {
      const data = {
        userName: this.userName,
        phoneNum: this.phoneNum,
        grade: "",
        pageNum: 1,
        pageSize: 10000,
        brandPartyId:this.supplierInfo.brandPartyId
      }
      if (this.typeTitle == '加盟商列表') {
        this.$api.franchiseeGetFranchiseeList(data).then(res => {
          this.supplierData = res.data
        })
      } else {
        this.$api.storeManagerGetStoreManagerList(data).then(res => {
          this.supplierData = res.data
        })
      }
    },
    handleOpen(val) {
      this.dialogVisible = true
      if (val) {
        this.title = '编辑'
        Object.keys(this.supplierInfo).forEach(key => {
          if (val.hasOwnProperty(key)) {
            this.supplierInfo[key] = val[key]
          }
        })
        this.supplierInfo.storeVariety = val.storeVariety.toString()
        this.supplierInfo.type = val.type.toString()
        this.supplierInfo.franchiseeId = val.nickName
        this.recordId = val.franchiseeId
        this.supplierInfo.storeUserId = val.storeManagerPhone
        this.recordStoreId = val.storeUserId
        this.supplierInfo.id = val.storeId
      } else {
        this.title = '新增'
        Object.assign(this.supplierInfo, this.$options.data.call(this).supplierInfo)
        this.$nextTick(() => {
          this.$refs.supplierForm?.clearValidate?.(); // 清除校验状态
        });
      }
      this.$api.storeGetBrandPartyVoById().then(res => {
        this.brandList = res
      })
      this.$api.storeGetFranchiseeByName().then(res => {
        this.supplierList = res
      })
    },
    openEarth() {
      this.$refs.initMapD.handleOpen()
    },
    receiveMessage(data) {
      this.supplierInfo.address = data.address
      this.supplierInfo.lat = data.latitude
      this.supplierInfo.lon = data.longitude
    },
    async chooseS(val) {
      this.userName = ''
      this.phoneNum = ''
      this.supplierDialog = true
      if (val == 'F') {
        this.typeTitle = '加盟商列表'
        const supplierData = await this.$api.franchiseeGetFranchiseeList({pageSize: 10000, pageNum: 1,brandPartyId:this.supplierInfo.brandPartyId}).then()
        this.supplierData = supplierData.data
      } else {
        this.typeTitle = '店长列表'
        const supplierData = await this.$api.storeManagerGetStoreManagerList({pageSize: 10000, pageNum: 1,brandPartyId:this.supplierInfo.brandPartyId}).then()
        this.supplierData = supplierData.data
      }
    },
    async _submit() {
      this.$refs.supplierForm.validate(async (valid) => {
        if (!valid) return false;
        try {
          const apiMap = {
            '新增': this.$api.storeAdd,
            '编辑': this.$api.storeUpdate
          };
          const apiFunc = apiMap[this.title];
          if (!apiFunc) return;
          const submitData = {
            ...this.supplierInfo,
            franchiseeId: this.recordId,
            storeUserId: this.recordStoreId
          }
          const resDate = await apiFunc(submitData);
          if (resDate == 1) {
            this.$message.success(`${this.title}成功！`);
            this.dialogVisible = false;
            this.$emit('addStatus', 1);
          }
        } catch (err) {
          console.error('接口请求出错：', err);
          this.$message.error('操作失败，请稍后重试');
        }
      });
    },
// this.$refs.supplierForm.validate(valid => {
//   if (valid) {
//     this.supplierInfo.franchiseeId = this.recordId
//     this.$api.storeAdd(this.supplierInfo).then(res => {
//       if (res == 1) {
//         this.$message.success('校验通过，提交成功！')
//         this.dialogVisible = false
//         this.$emit('addStatus', 1);
//       } else {
//         return false
//       }
//     })
//   } else {
//     this.$message.error('请完善所有必填项')
//   }
// })
// }

    handleSelectionChange(row) {
      this.recordInfo = row[0]
    },
    comfirm() {
      if (this.typeTitle == '加盟商列表') {
        this.supplierInfo.franchiseeId = this.recordInfo.franchiseeName
        this.supplierInfo.storePhone = this.recordInfo.franchiseePhone
        this.recordId = this.recordInfo.franchiseeId
      } else {
        this.supplierInfo.storeUserId = this.recordInfo.phoneNum
        this.recordStoreId = this.recordInfo.userId
      }
      this.supplierDialog = false
    },
    resetForm() {
      this.$refs.supplierForm.resetFields()
      this.recordId = ""
    }
  }
}
</script>
<style scoped>
.titleT {
  width: 120px;
  height: 38px;
  background-color: #F5F7FA;
  color: #909399;
  text-align: center;
  line-height: 40px;
  border-left: 1px solid #DCDFE6;
  border-top: 1px solid #DCDFE6;
  border-bottom: 1px solid #DCDFE6;
  border-bottom-left-radius: 3px;
  border-top-left-radius: 3px;
}

::v-deep .el-input__inner {
  border-top-left-radius: 0 !important;
  border-bottom-left-radius: 0 !important;
}

/deep/ .el-dialog__title {
  color: #fff;
}

/deep/ .el-dialog {
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

/deep/ .el-dialog__header {
  background-color: #303e9d;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

</style>